package cn.zjh.filter;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.core.Ordered;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.net.URI;

//记录请求的执行时长
public class MyGatewayFilter implements GatewayFilter, Ordered {

    //日志打印器
    private static Logger log = LoggerFactory.getLogger(MyGatewayFilter.class);

    //filter的核心方法
    //chain : 调用链对象，filter都是通过它来调用的
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {

        //开始时间
        exchange.getAttributes().put("startTime", System.currentTimeMillis());

        ServerHttpRequest request = exchange.getRequest();
        String path = request.getURI().getPath();
        log.info("gateway filter执行,请求的路径path = {}",path);

        //chain.filter : 继续执行下一个filter
        // then:执行完之后
        return chain.filter(exchange).then(
                //创建一个runnable线程
                Mono.fromRunnable(() -> {
                    //代码来到这，代表这个请求已经执行完了，现在要返回结果了

                    //开始时间
                    Long startTime = exchange.getAttribute("startTime");
                    //结束时间
                    Long endTime=(System.currentTimeMillis() - startTime);
                    log.info(exchange.getRequest().getURI().getRawPath() + ": " + endTime + "ms");
                })
        );
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
